<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Socket," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="网络上的两个程序通过一个双向的通信连接实现数据的交换，这个连接的一端称为一个socket。建立网络通信连接至少要一对端口号(socket)。socket本质是编程接口(API)，对TCP/IP的封装，TCP/IP也要提供可供程序员做网络开发所用的接口，这就是Socket编程接口；HTTP是轿车，提供了封装或者显示数据的具体形式;Socket是发动机，提供了网络通信的能力。Java Socket(">
<meta property="og:type" content="article">
<meta property="og:title" content="Java基础--Socket">
<meta property="og:url" content="https://zitongchen.github.io/2017/08/18/Java基础--Socket/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="网络上的两个程序通过一个双向的通信连接实现数据的交换，这个连接的一端称为一个socket。建立网络通信连接至少要一对端口号(socket)。socket本质是编程接口(API)，对TCP/IP的封装，TCP/IP也要提供可供程序员做网络开发所用的接口，这就是Socket编程接口；HTTP是轿车，提供了封装或者显示数据的具体形式;Socket是发动机，提供了网络通信的能力。Java Socket(">
<meta property="og:image" content="https://static.oschina.net/uploads/img/201707/10225239_S1Jv.png">
<meta property="og:image" content="https://static.oschina.net/uploads/img/201707/10225549_DKDm.png">
<meta property="og:image" content="https://static.oschina.net/uploads/img/201707/11083137_6bLG.png">
<meta property="og:image" content="https://static.oschina.net/uploads/img/201707/11091609_waPy.png">
<meta property="og:updated_time" content="2017-09-16T10:06:24.581Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java基础--Socket">
<meta name="twitter:description" content="网络上的两个程序通过一个双向的通信连接实现数据的交换，这个连接的一端称为一个socket。建立网络通信连接至少要一对端口号(socket)。socket本质是编程接口(API)，对TCP/IP的封装，TCP/IP也要提供可供程序员做网络开发所用的接口，这就是Socket编程接口；HTTP是轿车，提供了封装或者显示数据的具体形式;Socket是发动机，提供了网络通信的能力。Java Socket(">
<meta name="twitter:image" content="https://static.oschina.net/uploads/img/201707/10225239_S1Jv.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/08/18/Java基础--Socket/"/>





  <title> Java基础--Socket | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/08/18/Java基础--Socket/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java基础--Socket
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-18T00:00:00+08:00">
                2017-08-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/08/18/Java基础--Socket/" class="leancloud_visitors" data-flag-title="Java基础--Socket">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>网络上的两个程序通过一个双向的通信连接实现数据的交换，这个连接的一端称为一个socket。建立网络通信连接至少要一对端口号(socket)。socket本质是编程接口(API)，对TCP/IP的封装，TCP/IP也要提供可供程序员做网络开发所用的接口，这就是Socket编程接口；HTTP是轿车，提供了封装或者显示数据的具体形式;Socket是发动机，提供了网络通信的能力。<br>Java Socket(套接字)通常也称作”套接字”，用于描述IP地址和端口，是一个通信链的句柄。应用程序通常通过”套接字”向网络发出请求或者应答网络请求。</p>
</blockquote>
<p><img src="https://static.oschina.net/uploads/img/201707/10225239_S1Jv.png" alt="输入图片说明" title="在这里输入图片标题"><br>TCP/IP 是指 TCP 和 IP 这两种协议，同时TCP属于传输层，IP属于网络层；通常使用的网络（包括互联网）是在 TCP/IP 协议族的基础上运作<br>的。而 HTTP 属于它内部的一个子集。<br><img src="https://static.oschina.net/uploads/img/201707/10225549_DKDm.png" alt="输入图片说明" title="在这里输入图片标题"></p>
<p> 端口</p>
<ul>
<li>用于区分不同应用程序</li>
<li>端口的号范围0-65535，其中0-1023为系统所保留</li>
<li>IP地址和端口号组成了所谓的socket,socket是网络用运行的程序之间双向通信链路的终结点，是TCP和UDP的基础</li>
</ul>
<p>Java针对网络通信的不同层次，提供四大类网络功能</p>
<ul>
<li>InetAddress:用于标识网络上的硬件资源</li>
<li>URL：统一资源定位符，通过URL可以直接读取或写入网络上的数据</li>
<li>Sockets:使用TCP协议实现网络通信的Socket相关类</li>
<li>Datagram:使用UDP协议，将数据保存到数据报文中，通过网络进行通信</li>
</ul>
<h1 id="InetAddress"><a href="#InetAddress" class="headerlink" title="InetAddress"></a>InetAddress</h1><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InetAddressDemoOne</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> UnknownHostException </span>&#123;</div><div class="line">		<span class="comment">//获取本机的InetAddress对象</span></div><div class="line">		InetAddress address = InetAddress.getLocalHost();</div><div class="line">		System.out.println(<span class="string">"计算机名："</span> + address.getHostName());</div><div class="line">		System.out.println(<span class="string">"ip地址："</span> + address.getHostAddress());</div><div class="line">		<span class="comment">//打印InetAddress对象</span></div><div class="line">		System.out.println(<span class="string">"InetAddress对象:"</span> + address);</div><div class="line">		<span class="comment">//通过主机名获取InetAddress对象</span></div><div class="line">		InetAddress address1 = InetAddress.getByName(<span class="string">"Tony"</span>);</div><div class="line">		System.out.println(<span class="string">"计算机名："</span> + address1.getHostName());</div><div class="line">		System.out.println(<span class="string">"ip地址："</span> + address1.getHostAddress());</div><div class="line">		System.out.println(<span class="string">"InetAddress对象:"</span> + address1);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>代码输出结果：<br><figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">计算机名：Tony</div><div class="line">ip地址：192.168.56.1</div><div class="line">InetAddress对象:Tony/192.168.56.1</div><div class="line">计算机名：Tony</div><div class="line">ip地址：192.168.56.1</div><div class="line">InetAddress对象:Tony/192.168.56.1</div></pre></td></tr></table></figure></p>
<h1 id="URL"><a href="#URL" class="headerlink" title="URL"></a>URL</h1><p>使用URL读取网页内容</p>
<ul>
<li>通过URL对象的openStream()方法可以得到相应资源的数据输入流</li>
<li>通过输入流可以读取，访问网络上的数据</li>
</ul>
<p>URL的代码使用演示：<br><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UrlDemo</span> </span>&#123;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testUrlOne</span><span class="params">()</span> <span class="keyword">throws</span> MalformedURLException</span>&#123;</div><div class="line">		URL url = <span class="keyword">new</span> URL(<span class="string">"http://www.baidu.com:8080"</span>);</div><div class="line">		URL urlOne = <span class="keyword">new</span> URL(url, <span class="string">"/index.html?username=tony#one"</span>);</div><div class="line">		System.out.println(<span class="string">"协议："</span> + urlOne.getProtocol());</div><div class="line">		System.out.println(<span class="string">"主机： "</span> + urlOne.getHost());</div><div class="line">		<span class="comment">//若没有标明端口号，便会输出-1，现在标明端口号为8080，便输出8080</span></div><div class="line">		System.out.println(<span class="string">"端口："</span> + urlOne.getPort());</div><div class="line">		System.out.println(<span class="string">"文件路径："</span> + urlOne.getPath());</div><div class="line">		System.out.println(<span class="string">"文件名："</span> + urlOne.getFile());</div><div class="line">        System.out.println(<span class="string">"查询字符串："</span> + urlOne.getQuery());</div><div class="line">		System.out.println(<span class="string">"锚点位置："</span> + urlOne.getRef());</div><div class="line">		</div><div class="line">	&#125;</div><div class="line">	</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testUrlTwo</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			URL url = <span class="keyword">new</span> URL(<span class="string">"http://www.baidu.com"</span>);</div><div class="line">			<span class="comment">//通过openStream()方法得到指定资源的输入流</span></div><div class="line">			InputStream in = url.openStream();</div><div class="line">			<span class="comment">//通过输入流读取网络上的数据</span></div><div class="line">			InputStreamReader irs = <span class="keyword">new</span> InputStreamReader(in, <span class="string">"utf-8"</span>);</div><div class="line">			BufferedReader br = <span class="keyword">new</span> BufferedReader(irs);</div><div class="line">			String data = br.readLine();</div><div class="line">			<span class="keyword">while</span> (data != <span class="keyword">null</span>) &#123;</div><div class="line">				System.out.println(data);</div><div class="line">				data = br.readLine();</div><div class="line">			&#125;</div><div class="line">			br.close();</div><div class="line">			irs.close();</div><div class="line">			in.close();</div><div class="line">		&#125; <span class="keyword">catch</span> (MalformedURLException e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125; <span class="keyword">catch</span> (IOException ioe) &#123;</div><div class="line">			ioe.printStackTrace();</div><div class="line">		&#125;</div><div class="line">    &#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> MalformedURLException </span>&#123;</div><div class="line">		UrlDemo url = <span class="keyword">new</span> UrlDemo();</div><div class="line">        <span class="comment">//URL类的基本使用</span></div><div class="line">		url.testUrlOne();</div><div class="line">        <span class="comment">//读取网页中的内容</span></div><div class="line">		url.testUrlTwo();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>testUrlOne()方法输出的结果为：<br><figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">协议：http</div><div class="line">主机： www.baidu.com</div><div class="line">端口：8080</div><div class="line">文件路径：/index.html</div><div class="line">文件名：/index.html?username=tony</div><div class="line">锚点位置：one</div><div class="line">查询字符串：username=tony</div></pre></td></tr></table></figure></p>
<h1 id="Socket通信"><a href="#Socket通信" class="headerlink" title="Socket通信"></a>Socket通信</h1><p>TCP协议是面向连接，可靠的，有序的，以字节流的方式发送数据的</p>
<p>基于TCP协议实现的网络通信的类：</p>
<ul>
<li>客户端的Socket类</li>
<li>服务器端的ServerSocket类</li>
</ul>
<p><img src="https://static.oschina.net/uploads/img/201707/11083137_6bLG.png" alt="输入图片说明" title="在这里输入图片标题"></p>
<h2 id="Socket通信实现的步骤："><a href="#Socket通信实现的步骤：" class="headerlink" title="Socket通信实现的步骤："></a>Socket通信实现的步骤：</h2><ol>
<li>创建ServerSocket和Socket</li>
<li>打开连接到Socket的输出、输入流</li>
<li>按照协议对Socket进行读写操作</li>
<li>关闭输入输出流，关闭Socket</li>
</ol>
<h2 id="服务端的实现："><a href="#服务端的实现：" class="headerlink" title="服务端的实现："></a>服务端的实现：</h2><ol>
<li>创建ServerSocket对象</li>
<li>通过accept()方法监听客户端的请求</li>
<li>连接建立后，通过输入流读取客户端的请求信息</li>
<li>通过输出流向客户端发送响应信息</li>
<li>关闭相关资源</li>
</ol>
<h2 id="客户端的实现："><a href="#客户端的实现：" class="headerlink" title="客户端的实现："></a>客户端的实现：</h2><ol>
<li>创建Socket对象，指明需要连接的服务器地址</li>
<li>连接建立后，通过输出流向服务器端发送请求信息</li>
<li>通过输入流获取服务器响应的信息<br>4.关闭相关资源</li>
</ol>
<h2 id="多线程服务器实现："><a href="#多线程服务器实现：" class="headerlink" title="多线程服务器实现："></a>多线程服务器实现：</h2><ol>
<li>服务器端创建ServerSocket,循环调用accept()</li>
<li>客户端创建一个socket并和服务器端连接</li>
<li>服务端接受客户端请求，创建一个socket与该客户连接</li>
<li>建立连接的两个socket在一个单独的线程上对话</li>
<li>服务端继续等待新的连接</li>
</ol>
<h2 id="客户端的事例代码："><a href="#客户端的事例代码：" class="headerlink" title="客户端的事例代码："></a>客户端的事例代码：</h2><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Client</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createScoket</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			<span class="comment">//1.创建客户端Socket,指定服务器的地址与端口</span></div><div class="line">			Socket socket = <span class="keyword">new</span> Socket(<span class="string">"localhost"</span>, <span class="number">8080</span>);</div><div class="line">			<span class="comment">//2.获取输出流，向服务器发送信息</span></div><div class="line">			OutputStream os = socket.getOutputStream();</div><div class="line">			PrintWriter pw = <span class="keyword">new</span> PrintWriter(os);</div><div class="line">			pw.write(<span class="string">"用户名：tony; 密码： 1234"</span>);</div><div class="line">			pw.flush();</div><div class="line">			socket.shutdownOutput();</div><div class="line">			<span class="comment">//3.获取输入流，获取服务器的响应信息</span></div><div class="line">			InputStream is = socket.getInputStream();</div><div class="line">			BufferedReader br = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(is));</div><div class="line">			String info = <span class="keyword">null</span>;</div><div class="line">			<span class="keyword">while</span> ((info = br.readLine()) != <span class="keyword">null</span>) &#123;</div><div class="line">				System.out.println(<span class="string">"我是客户端，服务端说："</span> + info);</div><div class="line">			&#125;</div><div class="line">			<span class="comment">//4.关闭资源</span></div><div class="line">			socket.close();</div><div class="line">			</div><div class="line">		&#125; <span class="keyword">catch</span> (UnknownHostException uhe) &#123;</div><div class="line">			uhe.printStackTrace();</div><div class="line">		&#125; <span class="keyword">catch</span> (IOException ioe) &#123;</div><div class="line">			ioe.printStackTrace();</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">		Client client = <span class="keyword">new</span> Client();</div><div class="line">		client.createScoket();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="多线程类的事例代码："><a href="#多线程类的事例代码：" class="headerlink" title="多线程类的事例代码："></a>多线程类的事例代码：</h2><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServerThread</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</div><div class="line">	<span class="comment">//和本线程相关的Socket</span></div><div class="line">	<span class="keyword">private</span> Socket socket;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="title">ServerThread</span><span class="params">(Socket socket)</span> </span>&#123;</div><div class="line">		<span class="keyword">this</span>.socket = socket;</div><div class="line">	&#125;</div><div class="line">	<span class="comment">//线程执行的操作，响应客户端的请求</span></div><div class="line">	<span class="meta">@Override</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			InputStream is = socket.getInputStream();</div><div class="line">			InputStreamReader isr = <span class="keyword">new</span> InputStreamReader(is);</div><div class="line">			BufferedReader br = <span class="keyword">new</span> BufferedReader(isr);</div><div class="line">			OutputStream os = socket.getOutputStream();</div><div class="line">			PrintWriter pw = <span class="keyword">new</span> PrintWriter(os);</div><div class="line">			String info ;</div><div class="line">			<span class="keyword">while</span> ((info = br.readLine()) != <span class="keyword">null</span>) &#123;</div><div class="line">				System.out.println(<span class="string">"我是服务器，客户端说："</span> + info);</div><div class="line">			&#125;</div><div class="line">			socket.shutdownInput();</div><div class="line">			pw.write(<span class="string">"欢迎您！"</span>);</div><div class="line">			pw.flush();</div><div class="line">		&#125; <span class="keyword">catch</span> (IOException ioe) &#123;</div><div class="line">			ioe.printStackTrace();</div><div class="line">		&#125; <span class="keyword">finally</span> &#123;</div><div class="line">			<span class="keyword">try</span> &#123;</div><div class="line">				socket.close();</div><div class="line">			&#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">				e.printStackTrace();</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="服务端的事例代码："><a href="#服务端的事例代码：" class="headerlink" title="服务端的事例代码："></a>服务端的事例代码：</h2><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Server</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createServerSocket</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		ServerSocket serverSocket = <span class="keyword">new</span> ServerSocket(<span class="number">8080</span>);</div><div class="line">		Socket socket = <span class="keyword">null</span>;</div><div class="line">		<span class="keyword">int</span> count = <span class="number">0</span>;</div><div class="line">		System.out.println(<span class="string">"***服务器即将启动，等待客户端的连接***"</span>);</div><div class="line">		<span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</div><div class="line">			socket = serverSocket.accept();</div><div class="line">			<span class="comment">//创建一个线程</span></div><div class="line">			ServerThread servereThread = <span class="keyword">new</span> ServerThread(socket);</div><div class="line">			Thread thread = <span class="keyword">new</span> Thread(servereThread);</div><div class="line">			<span class="comment">//启动线程</span></div><div class="line">			thread.start();</div><div class="line">			count++;</div><div class="line">			System.out.println(<span class="string">"客户端的数量为："</span> + count);</div><div class="line">			System.out.println(<span class="string">"当前客户端的IP："</span> + socket.getInetAddress().getHostAddress());</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		Server  server = <span class="keyword">new</span> Server();</div><div class="line">		server.createServerSocket();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="UDP编程"><a href="#UDP编程" class="headerlink" title="UDP编程"></a>UDP编程</h1><p>进行数据传输时，首先需要将要传输的数据定义成数据报(Datagram），在数据报中指明数据所要送达的Socket(主机地址和端口号),然后再将数据报发送出去<br>UDP相关的操作类：</p>
<ul>
<li>DatagramPacket：表示数据报包</li>
<li>DatagramSocket：进行端到端通信的类</li>
</ul>
<h2 id="服务端（客户端）实现："><a href="#服务端（客户端）实现：" class="headerlink" title="服务端（客户端）实现："></a>服务端（客户端）实现：</h2><ol>
<li>创建DatagramSocket，指定端口号</li>
<li>创建DatagraPacket</li>
<li>接受客户端发送的数据信息</li>
<li>读取数据</li>
</ol>
<h2 id="客户端实现的事例代码："><a href="#客户端实现的事例代码：" class="headerlink" title="客户端实现的事例代码："></a>客户端实现的事例代码：</h2><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UDPClient</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createDatagramSocket</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		<span class="comment">/*</span></div><div class="line">		 * 向服务器发送数据</div><div class="line">		 */</div><div class="line">		<span class="comment">//1.定义服务器的地址，端口，数据</span></div><div class="line">		InetAddress adddress = InetAddress.getByName(<span class="string">"localhost"</span>);</div><div class="line">		<span class="keyword">int</span> port = <span class="number">8080</span>;</div><div class="line">		<span class="keyword">byte</span>[] data = <span class="string">"用户名：admin;密码：123"</span>.getBytes();</div><div class="line">		<span class="comment">//2.创建数据报，包含发送的数据信息</span></div><div class="line">		DatagramPacket packet = <span class="keyword">new</span> DatagramPacket(data, data.length, adddress, port);</div><div class="line">		<span class="comment">//3.创建DatagramSocket对象</span></div><div class="line">		DatagramSocket socket = <span class="keyword">new</span> DatagramSocket();</div><div class="line">		<span class="comment">//4.向服务端发送数据报</span></div><div class="line">		socket.send(packet);</div><div class="line">		</div><div class="line">		<span class="comment">/*</span></div><div class="line">		 * 接收服务器响应的数据</div><div class="line">		 */</div><div class="line">		<span class="comment">//1.创建数据报，用于接收服务器的响应数据</span></div><div class="line">		<span class="keyword">byte</span>[] data2 = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</div><div class="line">		DatagramPacket packet2 = <span class="keyword">new</span> DatagramPacket(data2, data2.length);</div><div class="line">		socket.receive(packet2);</div><div class="line">		String reply = <span class="keyword">new</span> String(data2, <span class="number">0</span>, packet2.getLength());</div><div class="line">		System.out.println(<span class="string">"我是客户端，服务器说："</span> + reply);</div><div class="line">		socket.close();</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		UDPClient clint = <span class="keyword">new</span> UDPClient();</div><div class="line">		clint.createDatagramSocket();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="服务端实现的事例代码："><a href="#服务端实现的事例代码：" class="headerlink" title="服务端实现的事例代码："></a>服务端实现的事例代码：</h2><figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UDPserver</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createUDPserverScoket</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		<span class="comment">/*</span></div><div class="line">		 * 接收客户端发送的数据</div><div class="line">		 */</div><div class="line">		<span class="comment">//1.创建服务器端的DatagramSocket ,指定端口，</span></div><div class="line">		DatagramSocket socket = <span class="keyword">new</span> DatagramSocket(<span class="number">8080</span>);</div><div class="line">		<span class="comment">//2.创建数据报，用于接收客户端发送的数据</span></div><div class="line">		<span class="keyword">byte</span>[] data = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</div><div class="line">		DatagramPacket packet = <span class="keyword">new</span> DatagramPacket(data, data.length);</div><div class="line">		<span class="comment">//3.接收客户端发送过来的数据报</span></div><div class="line">		System.out.println(<span class="string">"***服务器已经启动，等带客户端***"</span>);</div><div class="line">		socket.receive(packet);</div><div class="line">		String info = <span class="keyword">new</span> String(data, <span class="number">0</span>, packet.getLength());</div><div class="line">		System.out.println(<span class="string">"我是服务器，客户端说："</span> + info);</div><div class="line">		</div><div class="line">		<span class="comment">/*</span></div><div class="line">		 * 响应客户端数据</div><div class="line">		 */</div><div class="line">		<span class="comment">//1.定义客户端的地址，端口，数据</span></div><div class="line">		InetAddress address = packet.getAddress();</div><div class="line">		<span class="keyword">int</span> port = packet.getPort();</div><div class="line">		<span class="keyword">byte</span>[] data2 = <span class="string">"欢迎您！"</span>.getBytes();</div><div class="line">		<span class="comment">//2.创建数据报，包含响应的数据信息</span></div><div class="line">		DatagramPacket packet2 = <span class="keyword">new</span> DatagramPacket(data2, data2.length, address, port);</div><div class="line">		<span class="comment">//3.响应客户端</span></div><div class="line">		socket.send(packet2);</div><div class="line">		socket.close();</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		UDPserver server = <span class="keyword">new</span> UDPserver();</div><div class="line">		server.createUDPserverScoket();</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="经验与技巧："><a href="#经验与技巧：" class="headerlink" title="经验与技巧："></a>经验与技巧：</h1><ul>
<li>对于同一个socket,如果关闭了输出流，则与该输出流关联的socket也会被关闭，所以一般不要关闭流，关闭socket即可</li>
<li><p>多线程中，未设置优先级可能会导致运行时输出非常慢，可降低优先级</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">thread.setPriority(4)  //设置线程的优先级，范围为[1,10],默认为5</div></pre></td></tr></table></figure>
</li>
<li><p>使用TCP通信传递对象</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">ObjetctOutputStream oos  = new  ObjectOutputStream(os);</div><div class="line">User user = new User(&quot;admin&quot;, &quot;1234&quot;);</div><div class="line">oos.writeObject(user);</div></pre></td></tr></table></figure>
</li>
<li><p>sockete编程传递文件</p>
</li>
</ul>
<p><img src="https://static.oschina.net/uploads/img/201707/11091609_waPy.png" alt="输入图片说明" title="在这里输入图片标题"></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Socket/" rel="tag"># Socket</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/16/Java基础--反射/" rel="next" title="Java基础--反射">
                <i class="fa fa-chevron-left"></i> Java基础--反射
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/19/Java-IO学习笔记/" rel="prev" title="Java-IO学习笔记">
                Java-IO学习笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#InetAddress"><span class="nav-number">1.</span> <span class="nav-text">InetAddress</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#URL"><span class="nav-number">2.</span> <span class="nav-text">URL</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Socket通信"><span class="nav-number">3.</span> <span class="nav-text">Socket通信</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Socket通信实现的步骤："><span class="nav-number">3.1.</span> <span class="nav-text">Socket通信实现的步骤：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务端的实现："><span class="nav-number">3.2.</span> <span class="nav-text">服务端的实现：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#客户端的实现："><span class="nav-number">3.3.</span> <span class="nav-text">客户端的实现：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多线程服务器实现："><span class="nav-number">3.4.</span> <span class="nav-text">多线程服务器实现：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#客户端的事例代码："><span class="nav-number">3.5.</span> <span class="nav-text">客户端的事例代码：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多线程类的事例代码："><span class="nav-number">3.6.</span> <span class="nav-text">多线程类的事例代码：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务端的事例代码："><span class="nav-number">3.7.</span> <span class="nav-text">服务端的事例代码：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#UDP编程"><span class="nav-number">4.</span> <span class="nav-text">UDP编程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#服务端（客户端）实现："><span class="nav-number">4.1.</span> <span class="nav-text">服务端（客户端）实现：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#客户端实现的事例代码："><span class="nav-number">4.2.</span> <span class="nav-text">客户端实现的事例代码：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#服务端实现的事例代码："><span class="nav-number">4.3.</span> <span class="nav-text">服务端实现的事例代码：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#经验与技巧："><span class="nav-number">5.</span> <span class="nav-text">经验与技巧：</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
